<template>
    <div class="container">
        <!-- 设备名称 -->
        <div class="station-name">{{ info.station_name }}</div>
        <!-- 系列号 -->
        <div class="station-serial-num">{{ info.station_serial_num }}</div>
        <!-- 充电插口 -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">充电插口</div>
                <div class="card-header-right">
                    空闲{{ freeNum }} <span>/占用{{ inUseNum }}</span>
                </div>
            </div>
            <div class="card-content">
                <div class="port-item" :class="[index === portIndex ? 'selected' : '', item.can_charge ? '' : 'in-use']" v-for="(item, index) in portList" :key="index" @click="select(item, index)">
                    <div class="port-box">
                        {{ !item.can_charge ? "已占" : index === portIndex ? "已选" : "空闲" }}
                        <div class="selected-border"></div>
                    </div>
                    <div class="port-name" :class="[index === portIndex ? 'selected' : '']">{{ item.port }}号位</div>
                </div>
            </div>
        </div>
        <!-- 充电时长 -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">支付金额</div>
                <div class="card-header-right"></div>
            </div>
            <div class="card-content duration-content">
                <div class="duration-item" :class="[durationIndex === index ? 'selected' : '']" v-for="(item, index) in durationList" :key="index" @click="selectPrice(index)">
                    <template v-if="index === 7">{{ !item.price ? "自定义" : item.price + "元" }}</template>
                    <template v-else>{{ item.desc }}</template>
                </div>
            </div>
        </div>

        <!-- 预计充电费用 -->
        <!-- <div class="card">
                <div class="card-header">
                    <div class="card-title">支付金额</div>
                    <div class="card-header-right"></div>
                </div>
                <div class="card-content duration-content">
                    <div class="duration-item" :class="[durationIndex === index ? 'selected' : '']" v-for="(item, index) in durationList" :key="index" @click="selectPrice(index)">
                        <template v-if="index === 7">{{ !item.price ? "自定义" : item.price + "元" }}</template>
                        <template v-else>{{ item.desc }}</template>
                    </div>
                </div>
            </div> -->

        <!-- 预计充电费用 -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">预计充电费用</div>
                <div class="card-header-right"></div>
            </div>
            <!-- <div class="card-content">
                    <div class="form-item">
                        <div class="form-label">费用单价</div>
                        <div class="form-input">0.5元/小时</div>
                    </div>
                </div> -->
            <div class="info-footer">
                <div class="price">
                    实付金额: <span v-if="durationList[durationIndex].price / 1 != realPrice / 1" class="before-discount">￥{{ durationList[durationIndex].price }}</span
                    ><span class="real-price">￥{{ realPrice }}</span>
                </div>
            </div>
        </div>
        <!-- 计费规则 -->
        <div class="rule-content">
            <div class="rule-title">计费/退费规则</div>
            <div class="rule-desc" :class="{ important: item.special }" v-for="(item, index) in ruleList" :key="index"><span>·</span>{{ item.rule_desc }}</div>
        </div>

        <!-- 开始充电 -->
        <div class="footer">
            <div v-if="hasLogin" class="btn" @click="pay">开始充电</div>
            <div v-else class="btn" @click="toLogin">尚未登陆，点击去登录</div>
        </div>

        <!-- 自定义价格 -->
        <ant-number-keyboard :visible="keyboardVisible" @close="keyboardVisible = false" @change="customPriceChange"></ant-number-keyboard>
    </div>
</template>

<script>
import { getStationDetailAPI, createOrderAPI, getRealPriceAPI } from "../src/api/api";
import { getQueryString } from "../src/libs/utils";
import LoginButton from "../src/components/LoginButton.vue";

const app = getApp();

export default {
    components: {
        LoginButton,
    },
    data() {
        return {
            isWx: app.globalData.isWx,
            pageLoading: false,
            loading: false,
            userInfo: {},
            queryPort: "", // 页面port参数值
            portIndex: -1,
            stationSerialNumPort: "",

            durationIndex: 0,
            keyboardVisible: false,

            portList: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
            durationList: [
                {
                    desc: "充满自停",
                    price: 2, // 这里price的单位是元，下单时单位为分应乘以100
                },
                {
                    desc: "1元",
                    price: 1,
                },
                {
                    desc: "2元",
                    price: 2,
                },
                {
                    desc: "3元",
                    price: 3,
                },
                {
                    desc: "4元",
                    price: 4,
                },
                {
                    desc: "5元",
                    price: 5,
                },
                {
                    desc: "6元",
                    price: 6,
                },
                {
                    desc: "自定义",
                    price: "",
                },
            ],

            info: {},
            ruleList: [],
            portList: [],

            inUseNum: 0, // 使用数
            freeNum: 0, //空闲数

            minimumPrice: 0, // 最小支付金额
            hasAutoSelected: false,

            realPrice: "", // 真实价格

            hasLogin: false,
            inRecharging: false,
        };
    },
    watch: {
        durationIndex() {
            this.getRealPrice();
        },
        keyboardVisible(val) {
            console.log("关闭了");
            if (!val) {
                this.getRealPrice();
            }
        },
    },
    onShareAppMessage() {},
    onLoad(options) {
        console.log(this.durationList);
        console.log("options", options);
        // uni.getProvider({
        //     service: "payment",
        // }).then((res) => {
        //     console.log("getProvider", res);
        // });
        let { q, port, stationSerialNumPort } = options;

        // 扫码不传port则无默认选中充电口
        // 支付宝扫码跳转
        if (app.globalData.stationSerialNumPort) {
            this.stationSerialNumPort = app.globalData.stationSerialNumPort || "";
            this.queryPort = app.globalData.port || "";
        }
        // 微信扫码跳转
        else if (q) {
            let u = decodeURIComponent(q);
            this.stationSerialNumPort = getQueryString(u, "stationSerialNumPort") || "";
            this.queryPort = getQueryString(u, "port") || "";
        } else {
            this.stationSerialNumPort = stationSerialNumPort || "";
            this.queryPort = port || "";
        }
    },
    onShow() {
        uni.showLoading({
            title: "加载中",
        });
        this.pageLoading = true;
        app.login()
            .then((res) => {
                this.userInfo = res;
                this.hasLogin = !!res.phone;
                this.getStationList();
                uni.hideLoading();
                this.pageLoading = false;
            })
            .catch((err) => {
                uni.hideLoading();
                this.pageLoading = false;
            });
    },
    methods: {
        // 去登陆
        toLogin() {
            uni.navigateTo({
                url: "/pages/login",
            });
        },
        // 查询站点信息
        getStationList() {
            getStationDetailAPI({
                stationSerialNumPort: this.stationSerialNumPort || "",
            }).then((res) => {
                this.info = res || {};
                this.portList = res.station_port_list || [];
                this.ruleList = res.charge_rule || [];

                // 充满自停费用
                if (this.info.payment_vo && this.info.payment_vo.full_stop_price) {
                    this.durationList[0].price = this.info.payment_vo.full_stop_price / 100;
                }
                // 最小支付金额
                if (this.info.payment_vo && this.info.payment_vo.minimum_price) {
                    this.minimum_price = this.info.payment_vo.minimum_price;
                }

                // 计算优惠后价格
                this.getRealPrice();

                // 计算空闲/占用充电口数
                this.freeNum = 0;
                this.inUseNum = 0;
                this.portList.forEach((item, index) => {
                    if (item.can_charge) {
                        this.freeNum++;
                    } else {
                        this.inUseNum++;
                    }

                    // 热启动进入页面
                    if (this.hasAutoSelected) {
                        // 已经选中了某个充电口
                        if (this.portIndex === index && !item.can_charge) {
                            this.portIndex = -1;
                        }
                    }
                    // 冷启动进入页面 扫码指定口空闲就默认选中，使用中就提示
                    else {
                        if (this.queryPort - 1 === index) {
                            if (item.can_charge) {
                                this.portIndex = index;
                            } else {
                                uni.showToast({
                                    title: `${this.queryPort}号充电口使用中，请重新选择`,
                                    icon: "none",
                                });
                                this.portIndex = -1;
                            }
                        }
                    }
                });

                this.hasAutoSelected = true;
            });
        },
        // 计算优惠后价格
        getRealPrice() {
            console.log(this.durationList[this.durationIndex].price);
            getRealPriceAPI({ price: this.durationList[this.durationIndex].price * 100 }).then((res) => {
                this.realPrice = res / 100;
            });
        },
        // 选择充电口
        select(item, index) {
            if (item.can_charge) {
                this.portIndex = index;
            }
        },
        // 选择充电价格
        selectPrice(index) {
            this.durationIndex = index;
            if (index === 7) {
                this.keyboardVisible = true;
            }
        },
        // 自定义支付金额
        customPriceChange(e) {
            let n = this.isWx ? e.detail : e;
            // 加
            if (n) {
                // 首位已经是0 第二位必须是.
                if (this.durationList[7].price === "0" && n !== ".") {
                    return false;
                }
                // 首位不能为 . 或 0
                if (this.durationList[7].price.length === 0 && n === ".") {
                    return false;
                }
                // 不能有两个小数点
                if (n === "." && this.durationList[7].price.indexOf(".") !== -1) {
                    return false;
                }
                // 不能超过两位小数
                if (this.durationList[7].price.indexOf(".") !== -1 && this.durationList[7].price.split(".")[1].length >= 2) {
                    return false;
                }
                // 无小数时 整数位数不能超过4位
                if (this.durationList[7].price.indexOf(".") === -1 && this.durationList[7].price.length >= 4 && n !== ".") {
                    return false;
                }

                this.durationList[7].price += n;
            }
            // 删除
            else {
                if (this.durationList[7].price.length) {
                    this.durationList[7].price = this.durationList[7].price.slice(0, -1);
                }
            }
        },
        // 支付
        pay() {
            if (this.freeNum === 0) {
                uni.showToast({
                    title: `无空闲充电插口`,
                    icon: "none",
                });
                return false;
            }
            if (this.portIndex < 0) {
                uni.showToast({
                    title: `请选择充电插口`,
                    icon: "none",
                });
                return false;
            }
            if (this.loading) return false;
            this.loading = true;
            let amount = this.durationList[this.durationIndex].price / 1;
            if (amount < this.minimumPrice) {
                uni.showToast({
                    title: `最低消费不能小于${this.minimumPrice}元`,
                    icon: "none",
                });
                return false;
            }

            if (this.inRecharging) return false;
            this.inRecharging = true;
            uni.showLoading({
                title: "支付中",
            });
            createOrderAPI({
                amount: amount * 100,
                pay_type: this.isWx ? "WECHAT" : "ALIPAY",
                port: this.portList[this.portIndex].port,
                station_serial_num: this.info.station_serial_num,
            })
                .then((res) => {
                    this.loading = false;
                    try {
                        // 白名单或钱包支付
                        if (!res.charge_url) {
                            uni.showToast({
                                title: "下单成功",
                                icon: "none",
                            });
                            setTimeout(() => {
                                uni.navigateTo({
                                    url: `/pages/order_result?orderNo=${res.order_no}`,
                                });
                            }, 1500);
                            return false;
                        }
                        if (this.isWx) {
                            let chargeData = JSON.parse(res.charge_url);
                            uni.requestPayment({
                                timeStamp: chargeData.timeStamp,
                                nonceStr: chargeData.nonceStr,
                                package: chargeData.package,
                                signType: chargeData.signType,
                                paySign: chargeData.sign,
                                success: () => {
                                    uni.showToast({
                                        title: "支付成功",
                                        icon: "none",
                                    });
                                    setTimeout(() => {
                                        uni.navigateTo({
                                            url: `/pages/order_result?orderNo=${res.order_no}`,
                                        });
                                    }, 1500);
                                },
                                fail: (err) => {
                                    console.log("支付失败", err);
                                },
                                complete: () => {
                                    this.inRecharging = false;
                                    uni.hideLoading();
                                },
                            });
                        } else {
                            uni.requestPayment({
                                provider: "alipay",
                                tradeNO: JSON.parse(decodeURIComponent(res.charge_url)).tradeNo,
                                success: (response) => {
                                    if (response.resultCode === "9000") {
                                        uni.showToast({
                                            title: "支付成功",
                                            icon: "none",
                                        });
                                        setTimeout(() => {
                                            uni.navigateTo({
                                                url: `/pages/order_result?orderNo=${res.order_no}`,
                                            });
                                        }, 1500);
                                    } else {
                                        uni.showToast({
                                            title: "支付失败",
                                            icon: "none",
                                        });
                                    }
                                },
                                fail: (err) => {
                                    console.log("支付失败", err);
                                },
                                complete: () => {
                                    this.inRecharging = false;
                                    uni.hideLoading();
                                },
                            });
                        }
                    } catch (err) {
                        console.log("err", err);
                        this.loading = false;
                        this.inRecharging = false;
                        uni.hideLoading();
                    }
                })
                .catch((err) => {
                    this.loading = false;
                    this.inRecharging = false;
                    uni.hideLoading();
                });
        },
    },
};
</script>

<style scoped lang="less">
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #f6f6f6;
    min-height: 100vh;
    color: #333;
    box-sizing: border-box;
    padding-top: 30rpx;
    padding-bottom: 240rpx;

    .station-name {
        width: 694rpx;
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
        padding-left: 20rpx;
        color: #222;
    }

    .station-serial-num {
        width: 694rpx;
        font-size: 24rpx;
        margin-bottom: 20rpx;
        padding-left: 20rpx;
        color: #666;
    }

    .card {
        box-sizing: border-box;
        width: 694rpx;
        padding: 28rpx;
        background-color: #fff;
        border-radius: 24rpx;
        margin-bottom: 24rpx;

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .card-title {
                font-size: 32rpx;
                line-height: 42rpx;
                font-weight: bold;
            }

            .card-header-right {
                font-size: 28rpx;
                line-height: 32rpx;

                span {
                    color: #9a9a9a;
                    margin-left: 10rpx;
                }
            }
        }

        .card-content {
            display: flex;
            flex-wrap: wrap;

            .port-item {
                width: 84rpx;
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-top: 30rpx;
                margin-right: 26rpx;

                &:nth-child(6n) {
                    margin-right: 0;
                }

                .port-box {
                    position: relative;
                    width: 84rpx;
                    height: 84rpx;
                    background-image: linear-gradient(136.39deg, #8bdab0 0%, #08bfa8 100%);
                    color: #fff;
                    border-radius: 20rpx;
                    margin-bottom: 8rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 22rpx;
                    box-sizing: border-box;

                    .selected-border {
                        position: absolute;
                        top: -6rpx;
                        width: 96rpx;
                        height: 96rpx;
                        border: 2rpx solid #08bfa8;
                        border-radius: 26rpx;
                        box-sizing: border-box;
                        display: none;
                    }
                }

                .port-name {
                    font-size: 24rpx;
                    line-height: 32rpx;
                    color: #656565;

                    &.selected {
                        color: #08bfa8;
                    }
                }

                &.in-use {
                    .port-box {
                        background-image: none;
                        background-color: #f6f6f6;
                        color: #cbcbcb;
                        border: 1rpx solid #cbcbcb;

                        .port-name {
                            color: #cbcbcb;
                        }
                    }
                }

                &.selected {
                    .port-box {
                        background-image: none;
                        background-color: #08bfa8;

                        .selected-border {
                            display: block;
                        }
                    }
                }
            }

            .duration-item {
                width: 138rpx;
                height: 84rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #f6f6f6;
                color: #9a9a9a;
                font-size: 28rpx;
                border-radius: 12rpx;
                margin-top: 28rpx;

                &.selected {
                    background-color: #08bfa8;
                    color: #fff;
                }
            }

            .form-item {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 28rpx;
                font-size: 28rpx;
                line-height: 36rpx;

                .form-label {
                    color: #9a9a9a;
                }
            }
        }

        .info-footer {
            width: 100%;
            display: flex;
            justify-content: flex-end;
            margin-top: 36rpx;

            .price {
                display: flex;
                align-items: flex-end;
                font-size: 28rpx;
                line-height: 38rpx;

                .before-discount {
                    font-size: 28rpx;
                    line-height: 36rpx;
                    text-decoration: line-through;
                }

                .real-price {
                    font-size: 36rpx;
                    line-height: 40rpx;
                    color: #ff5e5e;
                    font-weight: bold;
                }
            }
        }

        .duration-content {
            justify-content: space-between;
        }
    }

    .rule-content {
        width: 694rpx;

        .rule-title {
            font-size: 28rpx;
            line-height: 40rpx;
            font-weight: bold;
            padding-left: 10rpx;
            margin-bottom: 10rpx;
        }

        .rule-desc {
            padding-left: 10rpx;
            color: #666;
            font-size: 22rpx;
            line-height: 30rpx;
            margin-bottom: 5rpx;
            display: flex;
            align-items: center;

            span {
                font-weight: bold;
                margin-right: 5rpx;
            }

            &.important {
                color: #ff5e5e;
            }
        }
    }

    .footer {
        position: fixed;
        width: 100%;
        height: 100px;
        left: 0;
        bottom: 0;
        display: flex;
        justify-content: center;
        background-color: #f6f6f6;

        .btn {
            margin-top: 30rpx;
            width: 694rpx;
            height: 84rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(90deg, #8bdab0 0%, #08bfa8 100%);
            color: #fff;
            border-radius: 42rpx;
        }
    }
}
</style>
